package com.quark.util;

import com.quark.model.system.user.AdminUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author 张高昌
 * @date 2021/12/12 15:58
 * @description 安全工具类
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return
     */
    public AdminUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof AdminUser) {
            return (AdminUser) principal;
        }

        return null;
    }

    /**
     * 获取用户
     */
    public AdminUser getUser() {
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

    public Long getUserId() {
        Authentication authentication = getAuthentication();
        AdminUser user = getUser(authentication);

        return user.getId();
    }
}
